package com.core.locator;

import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.HibernateException;

import com.core.pf.Context;
import com.core.pf.PersistentException;

/**
 * 
 * @author jorge
 *
 */
public class ServiceLocator {
    
    // Atributos
    private SessionFactory sessionFactory;
    private Configuration config;
    private static ServiceLocator serviceLocator;

   /**
    * Constructor
    */
    private ServiceLocator() {
    }
    
    /**
     * 
     * @return
     */
    public static ServiceLocator getInstance() {
        if(serviceLocator == null)
            serviceLocator = new ServiceLocator();
        
        return serviceLocator;
    }
        
    /**
     * Obtengo la instancia de la sessionFactory
     * 
     * @return
     */
    public static SessionFactory getInstanceSessionFactory() {
        try {
            if(serviceLocator == null) {
                serviceLocator = ServiceLocator.getInstance();
            }
            if(serviceLocator.getConfig() == null) {
                serviceLocator.setConfig(Context.initialContext());
            }    
            if(serviceLocator.getSessionFactory() == null) {
                serviceLocator.setSessionFactory(serviceLocator.getConfig().configure().buildSessionFactory());
            }
            
            return serviceLocator.getSessionFactory();
        }
        catch(HibernateException hex) {
            throw new PersistentException("[ServiceLocator] Error grave al obtener una sesionFactory hibernate", null, hex);
        }
     }
    
    // Getters
    private Configuration getConfig() {
        return config;
    }
    private SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    private void setConfig(Configuration config) {
        this.config = config;
    }
    private void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
	
    
}
